package admin

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path"
	"strconv"
	"suci-go-zero/internal/svc"
	"suci-go-zero/internal/types"
	"time"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stringx"
)

const maxFileSize = 10 << 20 // 10 MB

type UploadLogic struct {
	logx.Logger
	r      *http.Request
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(r *http.Request, svcCtx *svc.ServiceContext) UploadLogic {
	return UploadLogic{
		Logger: logx.WithContext(r.Context()),
		r:      r,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload() (resp *types.UpdateResp, err error) {
	l.r.ParseMultipartForm(maxFileSize)
	file, handler, err := l.r.FormFile("file")
	if err != nil {
		fmt.Println(err)
		return nil, errors.Wrap(err, "")
	}
	defer file.Close()

	fmt.Printf("Uploaded File: %+v\n", handler.Filename)
	fmt.Printf("File Size: %+v\n", handler.Size)
	fmt.Printf("MIME Header: %+v\n", handler.Header)

	fileExt := path.Ext(handler.Filename)

	fileId := strconv.Itoa(int(time.Now().UnixMilli())) + stringx.Randn(3)
	fileName := "AM" + fileId + fileExt

	filePath := "./static/" + time.Now().Format("2006-01-02")
	os.MkdirAll(filePath, os.ModePerm)

	tempFile, err := os.Create(path.Join(filePath, fileName))
	if err != nil {
		fmt.Println(err)
		return nil, errors.Wrap(err, "")
	}
	defer tempFile.Close()
	io.Copy(tempFile, file)

	return &types.UpdateResp{
		Id:       fileId,
		FileName: fileName,
		Src:      "http://127.0.0.1:" + strconv.Itoa(l.svcCtx.Config.Port) + "/api/common/static/" + time.Now().Format("2006-01-02") + "/" + fileName,
	}, nil
}
